package com.zfsn.okaria.instance

import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.ToastUtils
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
class AppPermissions {
    private object SingletonHolder {
        val INSTANCE = AppPermissions()
    }
    companion object {
        fun getInstance() = SingletonHolder.INSTANCE
    }
    fun requestStorage(success:()->Unit={}){
        realRequestPermission("风芒想使用“您设备的存储空间”，用于图片、视频的读取，保存使用",
                              arrayOf(Permission.MANAGE_EXTERNAL_STORAGE), success)
    }
    fun requestLocation(success:()->Unit={}){
        realRequestPermission("风芒想访问“您的位置”，获取市州频道，为您推荐更多本地内容。",arrayOf(Permission.ACCESS_FINE_LOCATION, Permission.ACCESS_COARSE_LOCATION),success)
    }
    fun realRequestPermission(textContent:String?,permissions: Array<String>, success:()->Unit={}){
        if(XXPermissions.isGranted(ActivityUtils.getTopActivity(),permissions)){
            success.invoke()
            return
        }

        XXPermissions.with(ActivityUtils.getTopActivity())
            // 申请多个权限
            .permission(permissions)
            // 设置权限请求拦截器（局部设置）
            //.interceptor(new PermissionInterceptor())
            // 设置不触发错误检测机制（局部设置）
            //.unchecked()
            .request(object : OnPermissionCallback {
                override fun onGranted(permissions: MutableList<String>, allGranted: Boolean) {
                    if (!allGranted) {
//                        Tips.show("获取部分权限成功，但部分权限未正常授予")
                        ToastUtils.showShort("获取部分权限成功，但部分权限未正常授予")
                        return
                    }
                    success.invoke()
                }

                override fun onDenied(permissions: MutableList<String>, doNotAskAgain: Boolean) {
                    if (doNotAskAgain) {
                        ToastUtils.showShort("被永久拒绝授权，请手动授予存储权限")
                        // 如果是被永久拒绝就跳转到应用权限系统设置页面
                        XXPermissions.startPermissionActivity(ActivityUtils.getTopActivity(), permissions)
                    } else {
                        ToastUtils.showShort("获取权限失败")
                    }
                }
            })
    }

}